<template>
  <j-modal
    switchFullscreen
            :title="title"
            :width="width"
            :visible="visible"
            :confirmLoading="confirmLoading"
            @ok="handleOk"
            @cancel="handleCancel"
            :destroyOnClose="true"
            cancelText="关闭">
        <a-spin :spinning="confirmLoading">
            <a-form :form="form">

                <a-form-item label="父级分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-tree-select
                            :disabled="disable"
                            style="width:100%;border: 0px;border: none;outline:none;"
                            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                            :treeData="treeData"
                            v-model="model.parentCode"
                            :replaceFields="{children: 'children', title: 'typeName', value: 'typeCode'}"
                            placeholder="无">
                    </a-tree-select>
                </a-form-item>

                <a-form-item label="分类名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-decorator="[ 'typeName', validatorRules.typeName]" placeholder="请输入分类名称"></a-input>
                </a-form-item>

              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="产品层级"

              >
                <cn-dict-select-tag :options="{value:'dictDataDesc',label:'dictDataDesc'}" :triggerChange="true"
                                   dictCode="type_level"
                                   v-decorator.trim="['typeLevel', validatorRules.typeLevel]"
                                   placeholder="请选择产品层级" />
              </a-form-item>
                <!--<a-form-item label="类型编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-decorator="[ 'code', validatorRules.code]" placeholder="请输入类型编号"></a-input>
                </a-form-item>-->

                <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <span style="font-size: 12px;color:red" slot="label">编号规则(注)</span>
                  <span style="font-size: 12px;color:red">
                    编号值前缀需和父节点保持一致,比如父级节点编号是A01则当前编号必须以A01开头
                  </span>
                </a-form-item>-->


            </a-form>
        </a-spin>
    </j-modal>
</template>

<script>

    import {httpAction, getAction} from '@/api/manage'
    import {getProductCategory} from '@/api/api'
    import {pick} from 'lodash'
    import JTreeSelect from '@/components/cn-form/JTreeSelect'

    export default {
        name: "SysCategoryModal",
        components: {
            JTreeSelect
        },
        data() {
            return {
                disable:false,
                form: this.$form.createForm(this),
                title: "操作",
                width: 800,
                visible: false,
                model: {},
                labelCol: {
                    xs: {span: 24},
                    sm: {span: 5},
                },
                wrapperCol: {
                    xs: {span: 24},
                    sm: {span: 16},
                },

                confirmLoading: false,
                validatorRules: {
                    typeCode: {
                        rules: [{
                            required: true, message: ''
                        }, {
                            validator: this.validateMyCode
                        }]
                    },
                    parentCode: {},
                    typeName: {rules: [{required: true, message: ''}]}
                },
                url: {
                    add:  window._CONFIG['domianURL'] + "/cnProductTypeController/saveOrUpdateEntity",
                    edit:  window._CONFIG['domianURL'] + "/cnProductTypeController/saveOrUpdateEntity",
                    checkCode:  window._CONFIG['domianURL'] + "/sys/category/checkCode",
                },
                expandedRowKeys: [],
                pidField: "parentCode",
                subExpandedKeys: [],
                treeData: [],
            }
        },
        created() {
        },
        methods: {
            loadTreeData(params) {
                getProductCategory(params).then((res) => {
                    if (res.success) {
                        for (let i = 0; i < res.result.length; i++) {
                            let temp = res.result[i];
                            this.treeData.push(temp);
                        }
                    }

                })
            },
            add() {
                this.edit({});
            },
            async edit(record) {
              this.treeData = []
                !this.disable && await this.loadTreeData();
                this.form.resetFields();
                this.model = Object.assign({}, record);
                this.visible = true;
                this.$nextTick(() => {
                    this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
                })
            },
            close() {
                this.$emit('close');
                this.visible = false;
            },
            handleOk() {
                const that = this;
                // 触发表单验证
                this.form.validateFields((err, values) => {
                    if (!err) {
                        that.confirmLoading = true;
                        let httpurl = this.url.add
                        let formData = Object.assign(this.model, values);
                        httpAction(httpurl, formData, 'post').then((res) => {
                            if (res.success) {
                                that.$message.success(res.message);
                                that.submitSuccess(formData)
                            } else {
                                that.$message.warning(res.message);
                            }
                        }).finally(() => {
                            that.confirmLoading = false;
                        })
                    }

                })
            },
            handleCancel() {
                this.close()
            },
            popupCallback(row) {
                this.form.setFieldsValue(pick(row, Object.keys(row)))
            },
            submitSuccess(formData) {
                this.$emit('ok')
                this.close()
            },
            getExpandKeysByPid(parentCode, arr, all) {
                if (parentCode && arr && arr.length > 0) {
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].key == parentCode) {
                            this.expandedRowKeys.push(arr[i].key)
                            this.getExpandKeysByPid(arr[i]['parentId'], all, all)
                        } else {
                            this.getExpandKeysByPid(parentCode, arr[i].children, all)
                        }
                    }
                }
            },
            validateMyCode(rule, value, callback) {
                let params = {
                    parentCode: this.form.getFieldValue('parentCode'),
                    typeCode: value
                }
                getAction(this.url.checkCode, params).then((res) => {
                    if (res.success) {
                        callback()
                    } else {
                        callback(res.message)
                    }
                })
            },


        },
        watch:{
            visible(v){
                if(!v){
                    this.disable = false;
                }
            }
        }
    }
</script>
